package cn.player.act.vod;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import cn.player.R;
import cn.player.act.BaseActivity;
import cn.player.entity.ColumnListItem;
import cn.player.utils.HanziToPinyin;
import cn.player.utils.HanziToPinyin.Token;
import cn.player.utils.HanziToPinyinForGingerbread;
import cn.player.view.CommentDialog;
import cn.player.view.MyLetterListView;
import cn.player.view.MyLetterListView.OnTouchingLetterChangedListener;
import cn.player.media.util.ParseUtil;

public class ColumnListActivity extends BaseActivity {

	private LinearLayout mLlLoading;
	private GridView listView;
	private DataAdapter dataAdapter;
	private List<ColumnListItem> columnList;
	private String column_info_URL = "http://m.news.cntv.cn/special/json/lm/index.json";
	private OnItemClickListener onItemClickListener;
	private OnTouchingLetterChangedListener LetterListViewListener;
	private MyLetterListView mLetterList;
	private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
	private String[] sections;// 存放存在的汉语拼音首字母
	private CommentDialog dialog;// 展示匹配字母

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.columnlist_more_activity);
		findViews();
		setListensers();
		initializeDate();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (columnList != null) {
			columnList.clear();
			columnList = null;
		}
		if (alphaIndexer != null) {
			alphaIndexer.clear();
			alphaIndexer = null;
		}
	}

	protected void findViews() {
		listView = (GridView) findViewById(R.id.columnList_more_list);
		mLetterList = (MyLetterListView) findViewById(R.id.letterlist);
		
		mLlLoading = (LinearLayout)findViewById(R.id.ll_loading);
		listView.setEmptyView(mLlLoading);
	}

	protected void initializeDate() {
		dialog = new CommentDialog(this, R.style.my_contact_dialog);
		initJsonData(column_info_URL);
	}

	protected void setListensers() {

		LetterListViewListener = new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {

				if (alphaIndexer != null && alphaIndexer.get(s) != null) {
					mLetterList.invalidate();
					int position = alphaIndexer.get(s);
					listView.setSelection(position);
					dialog.show();
					dialog.changeTextView(sections[position]);
				}
			}
		};

		onItemClickListener = new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View convertView,
					int position, long arg3) {
				
				Intent detailIntent = new Intent(mContext,ColumnDetailActivity.class);
				detailIntent.putExtra("columnID", columnList.get(position).getColumnID());
				startActivity(detailIntent);
				overridePendingTransition(R.anim.base_push_right_in,R.anim.base_fade_out);
			}

		};

		listView.setOnItemClickListener(onItemClickListener);
		mLetterList.setOnTouchingLetterChangedListener(LetterListViewListener);
	}

	@Override
	protected void initDataSuccess(String url, JSONObject response) {
		// TODO Auto-generated method stub
		super.initDataSuccess(url, response);
		fillData(response);
	}

	@Override
	protected void initDataFailed(String url, int errorNo, String strMsg) {
		// TODO Auto-generated method stub
		super.initDataFailed(url, errorNo, strMsg);
	}

	private void fillData(JSONObject result) {
		try {
			JSONObject dataObj = result.optJSONObject("data");
			columnList = ParseUtil.parseDataToCollection(dataObj, "columnList",ColumnListItem.class);
			// 列表按照字母排序
			if (columnList != null && columnList.size() > 0) {
				int column_size = columnList.size();
				for (int i = 0; i < column_size; i++) {
					String name = columnList.get(i).getColumnName();
					columnList.get(i).setSortKey(getSortKey(name));
				}
				charSortNew(columnList);
			}

			// 存放字母列表对应关系
			alphaIndexer = new HashMap<String, Integer>();
			sections = new String[columnList.size()];
			for (int i = 0; i < columnList.size(); i++) {
				// 当前汉语拼音首字母
				String currentStr = getAlpha(columnList.get(i).getSortKey());
				// 上一个汉语拼音首字母，如果不存在为“ ”
				String previewStr = (i - 1) >= 0 ? getAlpha(columnList.get(i - 1).getSortKey()) : " ";
				if (!previewStr.equals(currentStr)) {
					String name = getAlpha(columnList.get(i).getSortKey());
					alphaIndexer.put(name, i);
					sections[i] = name;
				}
			}

			if (dataAdapter == null) {
				dataAdapter = new DataAdapter(columnList);
				listView.setAdapter(dataAdapter);
			} else {
				dataAdapter.setData(columnList);
				dataAdapter.notifyDataSetChanged();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// 获得汉语拼音首字母
	private String getAlpha(String str) {
		// 针对三个特殊联系人，其sortKey设为NULL，直接返回
		if (str == null) {
			return "语";
		}

		if (str.trim().length() == 0) {
			return "#";
		}

		char c = str.trim().substring(0, 1).charAt(0);
		// 正则表达式，判断首字母是否是英文字母
		Pattern pattern = Pattern.compile("^[A-Za-z]+$");
		if (pattern.matcher(c + "").matches()) {
			return (c + "").toUpperCase(Locale.getDefault());
		} else {
			return "#";
		}
	}

	private class DataAdapter extends BaseAdapter {

		private List<ColumnListItem> data;
		private ViewHolder viewHolder;

		public DataAdapter(List<ColumnListItem> data) {
			super();
			this.data = data;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return data.size();
		}

		@Override
		public Object getItem(int index) {
			// TODO Auto-generated method stub
			return data.get(index);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(R.layout.columnlist_more_row, null);
				viewHolder = new ViewHolder();
				viewHolder.row_img = (ImageView) convertView.findViewById(R.id.row_img);
				viewHolder.row_title = (TextView) convertView.findViewById(R.id.row_title);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			finalBitmap.display(viewHolder.row_img, data.get(position).getColumnImage());
			viewHolder.row_title.setText(data.get(position).getColumnName());
			return convertView;
		}

		public void setData(List<ColumnListItem> data) {
			this.data = data;
		}

		class ViewHolder {
			ImageView row_img;
			TextView row_title;
		}
	}

	// 根据4.0和2.x两种不同版本生成sortkey
	public String getSortKey(String source) {
		String sortKey;
		if (Build.VERSION.SDK_INT >= 14) {
			ArrayList<Token> tokens = null;
			tokens = HanziToPinyin.getInstance().get(source);
			StringBuilder sb = new StringBuilder();
			if (tokens != null && tokens.size() > 0) {
				for (Token ken : tokens) {
					if (Token.PINYIN == ken.type) {
						sb.append(ken.target.toLowerCase(Locale.getDefault())).append(ken.source);
					} else {
						sb.append(ken.source.toLowerCase(Locale.getDefault()));
					}
				}
			}
			sortKey = sb.toString();
		} else {
			ArrayList<HanziToPinyinForGingerbread.Token> tokens = null;
			tokens = HanziToPinyinForGingerbread.getInstance().get(source);
			StringBuilder sb = new StringBuilder();
			if (tokens != null && tokens.size() > 0) {
				for (HanziToPinyinForGingerbread.Token ken : tokens) {
					if (Token.PINYIN == ken.type) {
						sb.append(ken.target.toLowerCase(Locale.getDefault())).append(ken.source);
					} else {
						sb.append(ken.source.toLowerCase(Locale.getDefault()));
					}
				}
			}
			sortKey = sb.toString();
		}
		char c = '#';
		if (sortKey != null && !sortKey.equals("")) {
			c = sortKey.trim().substring(0, 1).charAt(0);
		}
		// 正则表达式，判断首字母是否是英文字母
		Pattern pattern = Pattern.compile("^[A-Za-z0-9]+$");
		if (pattern.matcher(c + "").matches()) {
		} else {
			sortKey = "9999";
		}
		return sortKey;
	}

	/*
	 * 字母排序
	 */
	public void charSortNew(List<ColumnListItem> listContactnew) {
		ContentComparatorNew cmp = new ContentComparatorNew();
		Collections.sort(listContactnew, cmp);
	}

	class ContentComparatorNew implements Comparator<ColumnListItem> {

		@Override
		public int compare(ColumnListItem lhs, ColumnListItem rhs) {
			return lhs.getSortKey().compareTo(rhs.getSortKey());
		}
	}

}
